package com.ocom.mqsimple.utils.wechatmsg;

import com.alibaba.fastjson.JSONObject;
import com.ocom.common.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ys
 * @ClassName WechatUtil
 * @Version 1.0
 */
@Slf4j(topic = "WxChatSendUtil")
@Component
public class WxChatSendUtil {

//    @Value("${bussiness.appId}")
//    private static String appId;
//    @Value("${bussiness.secret}")
//    private static String secret;
//    @Value("${bussiness.orderPlacementNoticeTemplateId}")
//    private static String orderPlacementNoticeTemplateId;

    private static final String appId="wx47714cc06dc601e2";
    private static final String secret="951f1946940aa221679e476740a2cb05";
    private static final String orderPlacementNoticeTemplateId="p920DJFWZsVO-FFUrAZeB0xsFx4WmFyC4WjK-xgqSSI";

    //W6ylPLBeb07VldS7c4HTWRfnfeC7BPnLL4lo3y2guJY  充值
    /**
     * 详细内容
     * 学员姓名
     * {{phrase2.DATA}}
     * 充值金额
     * {{amount4.DATA}}
     * 充值时间
     * {{time6.DATA}}
     * 卡内余额
     * {{amount8.DATA}}
     * 账户类型
     * {{phrase7.DATA}}
     */

    //p920DJFWZsVO-FFUrAZeB0xsFx4WmFyC4WjK-xgqSSI 消费

    /**
     * 账户名称
     * {{thing5.DATA}}
     * 消费地点
     * {{thing3.DATA}}
     * 消费时间
     * {{time4.DATA}}
     * 消费金额
     * {{amount2.DATA}}
     * 账户余额
     * {{amount6.DATA}}
     */

    /**
     * 获取小程序token
     * @return
     */
    public static String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret + "&grant_type=client_credential";
        PrintWriter out = null;
        BufferedReader in = null;
        String line;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性 设置请求格式
            //设置返回类型
            conn.setRequestProperty("contentType", "text/plain");
            //设置请求类型
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setDoOutput(true);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
            return jsonObject.getString("access_token");

        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 发送微信小程序订阅消息
     *
     * @param wxSendParam
     * @return
     */
    public static String WxChatSendOrderNotice(WxSendParam wxSendParam) {
        // 1、获取 接口调用凭证
        RestTemplate restTemplate = new RestTemplate();
    //    String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxChatSendUtil.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + wxSendParam.getToken();
        //拼接推送的模版
        WxMssVO wxMssVo = new WxMssVO();
        //用户的openId
        wxMssVo.setTouser(wxSendParam.getBusinessOpenId());
        //订阅消息模板id
        wxMssVo.setTemplate_id(wxSendParam.getTemplateId());
        wxMssVo.setPage("pages/order/order");

        if (!CommonUtil.isNull(wxSendParam.getUrl())) {
            wxMssVo.setUrl(wxSendParam.getUrl());
        }

        wxMssVo.setData(wxSendParam.getOrderMap());
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }


    public static String WxChatSendOrderNotice1(WxSendParam wxSendParam) {
        // 1、获取 接口调用凭证
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVO wxMssVo = new WxMssVO();
        //用户的openId
        wxMssVo.setTouser(wxSendParam.getBusinessOpenId());
        //订阅消息模板id
        wxMssVo.setTemplate_id(wxSendParam.getTemplateId());
        wxMssVo.setPage("pages/order/order");

        wxMssVo.setData(wxSendParam.getOrderMap());
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }

    public static void main(String[] args) {
//        WxSendParam wxSendParam = new WxSendParam();
//        Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
//        orderSendWxSend.put("phrase2", new TemplateData("李老师"));
//        orderSendWxSend.put("amount4", new TemplateData("95元"));
//        orderSendWxSend.put("time6", new TemplateData("2022-02-03 09:13:34"));
//        orderSendWxSend.put("amount8", new TemplateData("99.18元"));
//        orderSendWxSend.put("phrase7", new TemplateData("学生"));
//        wxSendParam.setOrderMap(orderSendWxSend);
//        wxSendParam.setBusinessOpenId("o9Lpl6tf5vIpTyYC-wypAlzgGyNQ");
//        wxSendParam.setTemplateId("W6ylPLBeb07VldS7c4HTWRfnfeC7BPnLL4lo3y2guJY");
//        String mes  = WxChatSendUtil.WxChatSendOrderNotice1(wxSendParam);
//        System.out.println(mes);

        WxSendParam wxSendParam = new WxSendParam();
        Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
        orderSendWxSend.put("thing5", new TemplateData("李老师"));
        orderSendWxSend.put("thing3", new TemplateData("饭堂"));
        orderSendWxSend.put("time4", new TemplateData("2024-07-03 09:13:34"));
        orderSendWxSend.put("amount2", new TemplateData("99.18元"));
        orderSendWxSend.put("amount6", new TemplateData("2000.95元"));
        wxSendParam.setOrderMap(orderSendWxSend);
        wxSendParam.setBusinessOpenId("o9Lpl6tf5vIpTyYC-wypAlzgGyNQ");
        wxSendParam.setTemplateId("p920DJFWZsVO-FFUrAZeB0xsFx4WmFyC4WjK-xgqSSI");
        String mes  = WxChatSendUtil.WxChatSendOrderNotice1(wxSendParam);
        System.out.println(mes);
    }
}

